<template>
<div>
  <h3>{{msg}}</h3>
  <a href="javascript:void(0)" @click="showAddForm">添加</a>
  <table border="1" width="100%">
    <tr>
      <td>id</td>
      <td>name</td>
      <td>score</td>
      <td>操作</td>
    </tr>
    <tr v-for="(stu,idx) in stus" :key="stu.id">
      <td>{{stu.id}}</td>
      <td>{{stu.name}}</td>
      <td>{{stu.score}}</td>
      <td>
        <a href="javascript:void(0)" @click="modifyQuery(stu.id)">修改</a>
        <a href="javascript:void(0)" @click="removeStu(stu.id)">删除</a>
      </td>
    </tr>
  </table>

  <form action="" v-show="showForm">
    <input type="hidden" v-model="stu.id"><br/>
    name:<input type="text" v-model="stu.name"><br/>
    score:<input type="text" v-model="stu.score"><br/>
    <input type="button" value="保存" @click="savaStu">
  </form>
</div>
</template>

<script>
import instance from "../../utils/request";


export default {
name: "index",
  data(){
    return {
      msg:"学生管理",
      stus:[],
      stu:{},
      showForm:false
    }
  },
  created() {
  //调用函数 查所有
  this.queryAllStu();
  },
  methods:{
    queryAllStu(){
      //发异步请求 查所有
      instance.get("/stu/queryAll")
      .then(res=> this.stus=res.data);
    },
    modifyQuery(id){
      this.showForm = true;
      //发异步请求 查一个
      instance.get("/stu/modifyQuery?id="+id)
      .then(res=>this.stu=res.data);

    },
    savaStu(){
      if(this.stu.id) {
        //发异步请求 修改
        instance.post("/stu/modifySava", this.stu)
          .then(res => {
            this.stu = {};
            this.showForm = false;
            this.queryAllStu();
          });
      }else {
        //发异步请求 添加
        instance.post("/stu/regist", this.stu)
          .then(res => {
            this.stu = {};
            this.showForm = false;
            this.queryAllStu();
          });

      }
    },
    removeStu(id) {
      this.showForm = false;
      if (window.confirm("确认删除吗？")) {
        //发异步请求 删除
        instance.get("/stu/remove?id=" + id)
          .then(res => this.queryAllStu())
      }
    },
    showAddForm(){
      this.stu = {};
      this.showForm = true;
    }
  }
}
</script>

<style scoped>

</style>
